#
# This file is part of the kernelstudio package.
#
# (c) 2014-2025 zlin <admin@kernelstudio.com>
#
# For the full copyright and license information, please view the LICENSE file
# that was distributed with this source code.
import logging
import os

from ksai.document.converter.converter import document_converter, DocumentConverterException
from ksai.persistence.storage.attachment import Attachment
from ksai.utils.paths import get_project_storage_path

logger = logging.getLogger(__name__)


def convert_attachment(attachment: Attachment, target_suffix: str) -> bytes:
    if attachment.suffix == target_suffix:
        return attachment.content

    source_filepath = attachment.filepath
    if not os.path.isfile(source_filepath):
        source_filepath = get_project_storage_path(source_filepath)

    if not os.path.isfile(source_filepath):
        raise FileNotFoundError(source_filepath)

    target_filepath = source_filepath.split('.')[0] + '.' + target_suffix

    if document_converter.convert(source_filepath, target_filepath):
        try:
            # 先读取文件内容
            with open(target_filepath, 'rb') as f:
                content = f.read()

            # 然后删除文件
            os.remove(target_filepath)
            return content
        except Exception as e:
            # 错误处理
            logger.error(f"Failed to read and delete file: {str(e)}")
            raise DocumentConverterException(e)

    raise DocumentConverterException(f"{source_filepath} not convertable to {target_filepath}")
